package com.adnaan.backend.controller.wechat;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.adnaan.backend.common.annotation.RateLimiter;
import com.adnaan.backend.common.annotation.RestControllerMapping;
import com.adnaan.backend.common.model.PageParams;
import com.adnaan.backend.common.model.Result;
import com.adnaan.backend.entity.AfterSales;
import com.adnaan.backend.entity.Goods;
import com.adnaan.backend.entity.Order;
import com.adnaan.backend.entity.vo.OrderVo;
import com.adnaan.backend.service.AfterSalesService;
import com.adnaan.backend.service.GoodsService;
import com.adnaan.backend.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * author: adnaan
 * create: 2025-03-01 12:18
 * Description:
 */
@RestControllerMapping("/online-retailers")
public class OnlineRetailersController {

    @Resource
    private GoodsService goodsService;

    @Resource
    private OrderService orderService;

    @Resource
    private AfterSalesService afterSalesService;


    /**
     * 获取热销商品前5个
     */
    @GetMapping("/hot")
    @Operation(summary = "获取热销商品前5个")
    public Result<List<Goods>> getHotGoods() {
        return Result.success(goodsService.getHotGoods());
    }

    /**
     * 分页查询
     *
     * @param pageParams 筛选条件
     * @return 查询结果
     */
    @PostMapping("/list")
    @Operation(summary = "分页查询")
    public Result<Page<Goods>> queryByPage(@RequestBody PageParams<Goods> pageParams) {
        Goods params = pageParams.getParams();
        LambdaQueryWrapper<Goods> lqw = new LambdaQueryWrapper<>();
        lqw.like(params.getName() != null, Goods::getName, params.getName());
        lqw.eq(Goods::getStatus, 1);
        lqw.orderByDesc(Goods::getCreateTime);
        if (params.isPriceOrder()) {
            lqw.orderByAsc(Goods::getPrice);// 按价格排序 升序
        } else {
            lqw.orderByDesc(Goods::getCreateTime);// 按创建时间排序 降序
        }
        lqw.orderByDesc(Goods::getCreateTime);
        Page<Goods> page = goodsService.page(pageParams.getPage(), lqw);
        page.getRecords().forEach(item -> {
            item.setSales(orderService.count(new LambdaQueryWrapper<Order>().eq(Order::getGoodsId, item.getId())));
        });
        // 按销量排序
        if (params.isSalesOrder()) {
            page.getRecords().sort((o1, o2) -> o2.getSales().compareTo(o1.getSales()));
        }
        return Result.success(page);
    }

    /**
     * 分页查询
     *
     * @param pageParams 分页对象
     * @return 查询结果
     */
    @PostMapping("/order-page")
    @Operation(summary = "分页查询")
    public Result<Page<Order>> pageQuery(@RequestBody PageParams<Order> pageParams) {
        Order params = pageParams.getParams();
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        // 只能查看自己的订单
        Long userId = StpUtil.getLoginIdAsLong();
        lqw.eq(Order::getUserId, userId);
        lqw.eq(params.getStatus() != null, Order::getStatus, params.getStatus());
        lqw.orderByDesc(Order::getCreateTime);
        Page<Order> page = orderService.page(pageParams.getPage(), lqw);
        page.getRecords().forEach(item -> {
            Goods goods = goodsService.getById(item.getGoodsId());
            item.setGoodsName(goods.getName());
            // 商品图片是JSON数组字符串，先转为Json，再取第一个
            JSONArray jsonArray = JSONUtil.parseArray(goods.getCover());
            JSONObject img = jsonArray.getJSONObject(0);
            item.setGoodsImage(img.getStr("data"));
            item.setGoodsPrice(goods.getPrice());
            List<AfterSales> afterSalesList = afterSalesService.list(new LambdaQueryWrapper<AfterSales>().eq(AfterSales::getOrderId, item.getId()));
            if (!afterSalesList.isEmpty()) {
                AfterSales afterSales = afterSalesList.get(0); // 选择第一条记录
                item.setAfterSalesId(afterSales.getId());
            }

        });
        return Result.success(page);
    }

    /**
     * 创建订单
     *
     * @return 订单ID
     */
    @PostMapping("/create")
    @Operation(summary = "创建订单")
    public Result<Long> createOrder(@RequestBody OrderVo orderVo) {
        return Result.success(orderService.createOrder(StpUtil.getLoginIdAsLong(), orderVo));
    }

    /**
     * 支付
     *
     * @param id 订单ID
     */
    @GetMapping("/pay/{id}")
    @Operation(summary = "支付")
    public Result<Boolean> pay(@PathVariable Long id) {
        // 检查是否是订单的所有者
        Order order = orderService.getById(id);
        if (order == null) {
            return Result.error("订单不存在");
        }
        if (!order.getUserId().equals(StpUtil.getLoginIdAsLong())) {
            return Result.error("您无权支付此订单");
        }
        return Result.success(orderService.updateStatus(id, 1));
    }

    /**
     * 取消订单
     *
     * @param id 订单ID
     * @return 是否成功
     */
    @GetMapping("/cancel/{id}")
    @Operation(summary = "取消订单")
    public Result<Boolean> cancelOrder(@PathVariable Long id) {
        // 检查是否是订单的所有者
        Order order = orderService.getById(id);
        if (order == null) {
            return Result.error("订单不存在");
        }
        if (!order.getUserId().equals(StpUtil.getLoginIdAsLong())) {
            return Result.error("您无权取消此订单");
        }
        return Result.success(orderService.cancelOrder(id));
    }

    /**
     * 确认收货
     *
     * @param id 订单ID
     * @return 是否成功
     */
    @GetMapping("/confirm/{id}")
    @Operation(summary = "确认收货")
    public Result<Boolean> confirmReceive(@PathVariable Long id) {
        // 检查是否是订单的所有者
        Order order = orderService.getById(id);
        if (order == null) {
            return Result.error("订单不存在");
        }
        if (!order.getUserId().equals(StpUtil.getLoginIdAsLong())) {
            return Result.error("您无权确认此订单");
        }
        return Result.success(orderService.confirmReceive(id));
    }


    /**
     * 商品详情
     *
     * @param id 主键
     * @return 实例对象
     */
    @GetMapping("/goods-info/{id}")
    @Operation(summary = "商品详情")
    public Result<Goods> getGoodsById(@PathVariable Long id) {
        return Result.success(goodsService.getById(id));
    }

    /**
     * 创建售后申请
     *
     * @param afterSales 实例对象
     * @return 售后ID
     */
    @PostMapping("/createAfterSales")
    @Operation(summary = "创建售后申请")
    public Result<Long> createAfterSales(@RequestBody AfterSales afterSales) {
        Order order = orderService.getById(afterSales.getOrderId());
        if (order == null) {
            return Result.error("订单不存在");
        }
        Long userId = StpUtil.getLoginIdAsLong();
        if (!order.getUserId().equals(userId)) {
            return Result.error("您无权为此订单申请售后");
        }

        return Result.success(afterSalesService.createAfterSales(
                afterSales.getOrderId(),
                userId,
                afterSales.getType(),
                afterSales.getReason(),
                afterSales.getDescription(),
                afterSales.getImages()
        ));
    }

    @GetMapping("/after-sales/{id}")
    @Operation(summary = "查询售后详情")
    public Result<AfterSales> getAfterSalesById(@PathVariable Long id) {
        AfterSales afterSales = afterSalesService.getById(id);
        if (afterSales == null) {
            return Result.error("售后记录不存在");
        }
        Long userId = StpUtil.getLoginIdAsLong();
        if (!afterSales.getUserId().equals(userId)) {
            return Result.error("您无权查看此售后记录");
        }
        return Result.success(afterSales);
    }

    /**
     * 提醒发货
     *
     * @param id 订单ID
     * @return 是否成功
     */
    @GetMapping("/remind/{id}")
    @Operation(summary = "提醒发货")
    @RateLimiter(prefix = "remind", time = 3600, count = 1, message = "您已经提醒过啦，请稍后再来吧")
    public Result<Boolean> remind(@PathVariable Long id) {
        // 检查是否是订单的所有者
        Order order = orderService.getById(id);
        if (order == null) {
            return Result.error("订单不存在");
        }
        if (!order.getUserId().equals(StpUtil.getLoginIdAsLong())) {
            return Result.error("您无权提醒发货此订单");
        }
        return Result.success(orderService.remind(id));
    }
}
